import { useEffect, useRef } from 'react';

/**
 * Interval hook taken from: https://overreacted.io/making-setinterval-declarative-with-react-hooks/
 *
 * @param callback - Function to be called at each interval
 * @param delay - Delay in milliseconds (null to stop)
 */
const useInterval = (callback: () => void, delay: number | null): void => {
  const savedCallback = useRef<() => void | undefined>(undefined);

  // Remember the latest callback
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval
  useEffect(() => {
    function tick(): void {
      if (savedCallback.current) {
        savedCallback.current();
      }
    }

    if (delay !== null) {
      const id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
};

export default useInterval;

